import { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
import { WeatherService } from '../services/WeatherService';

interface WeatherQuery {
  city: string;
  type?: 'live' | 'forecast';
}

interface WeatherParams {
  city: string;
}

export default async function weatherRoutes(fastify: FastifyInstance) {
  const weatherService = new WeatherService();

  // 通用天气查询接口
  fastify.get<{
    Querystring: WeatherQuery;
  }>('/weather', {
    schema: {
      description: '获取天气信息',
      tags: ['天气'],
      querystring: {
        type: 'object',
        properties: {
          city: { 
            type: 'string', 
            description: '城市名称或城市编码（如：北京、110000）' 
          },
          type: { 
            type: 'string', 
            enum: ['live', 'forecast'],
            default: 'live',
            description: '天气类型：live-实时天气，forecast-天气预报' 
          },
        },
        required: ['city'],
      },
      response: {
        200: {
          type: 'object',
          properties: {
            success: { type: 'boolean' },
            message: { type: 'string' },
            data: {
              type: 'object',
              properties: {
                type: { type: 'string', enum: ['live', 'forecast'] },
                weather: { type: 'object' },
                formatted: { type: 'object' }
              },
            },
          },
        },
        400: {
          type: 'object',
          properties: {
            success: { type: 'boolean' },
            message: { type: 'string' },
            error: { type: 'string' },
          },
        },
      },
    },
    handler: async (request: FastifyRequest<{ Querystring: WeatherQuery }>, reply: FastifyReply) => {
      try {
        const { city, type = 'live' } = request.query;

        // 验证城市参数
        if (!weatherService.validateCity(city)) {
          return reply.status(400).send({
            success: false,
            message: '城市参数无效',
            error: '城市名称不能为空且长度不能超过50个字符'
          });
        }

        // 根据类型获取天气信息
        let result;
        if (type === 'forecast') {
          result = await weatherService.getForecastWeather(city);
        } else {
          result = await weatherService.getLiveWeather(city);
        }

        if (!result.success) {
          return reply.status(400).send(result);
        }

        console.log('WeatherService返回的result:', JSON.stringify(result, null, 2));
        console.log('result.data:', JSON.stringify(result.data, null, 2));
        console.log('result.data!.weather:', JSON.stringify(result.data!.weather, null, 2));
        console.log('准备格式化的weather数据:', JSON.stringify(result.data!.weather, null, 2));

        // 格式化数据
        const formatted = weatherService.formatWeatherData(result.data!.weather);
        console.log('格式化后的数据:', JSON.stringify(formatted, null, 2));

        const responseData = {
          success: true,
          message: '获取实时天气成功',
          data: {
            type: 'live',
            weather: JSON.parse(JSON.stringify(result.data!.weather)),
            formatted: JSON.parse(JSON.stringify(formatted))
          }
        };
        
        console.log('最终发送的响应数据:', JSON.stringify(responseData, null, 2));
        
        reply.type('application/json');
        return reply.send(JSON.stringify(responseData));

      } catch (error) {
        fastify.log.error(`天气查询失败: ${error instanceof Error ? error.message : String(error)}`);
        return reply.status(500).send({
          success: false,
          message: '服务器内部错误',
          error: error instanceof Error ? error.message : '未知错误'
        });
      }
    }
  });

  // 获取实时天气
  fastify.get<{
    Params: WeatherParams;
  }>('/weather/live/:city', {
    schema: {
      description: '获取指定城市的实时天气',
      tags: ['天气'],
      params: {
        type: 'object',
        properties: {
          city: { 
            type: 'string', 
            description: '城市名称或城市编码' 
          },
        },
        required: ['city'],
      },
      response: {
        200: {
          type: 'object',
          properties: {
            success: { type: 'boolean' },
            message: { type: 'string' },
            data: {
              type: 'object',
              properties: {
                type: { type: 'string' },
                weather: { type: 'object' },
                formatted: { type: 'object' }
              },
            },
          },
        },
      },
    },
    handler: async (request: FastifyRequest<{ Params: WeatherParams }>, reply: FastifyReply) => {
      try {
        const { city } = request.params;

        if (!weatherService.validateCity(city)) {
          return reply.status(400).send({
            success: false,
            message: '城市参数无效'
          });
        }

        const result = await weatherService.getLiveWeather(city);

        if (!result.success) {
          return reply.status(400).send(result);
        }

        const formatted = weatherService.formatWeatherData(result.data!.weather);

        return reply.send({
          success: result.success,
          message: result.message,
          data: {
            type: result.data!.type,
            weather: result.data!.weather,
            formatted
          }
        });

      } catch (error) {
        fastify.log.error(`实时天气查询失败: ${error instanceof Error ? error.message : String(error)}`);
        return reply.status(500).send({
          success: false,
          message: '服务器内部错误'
        });
      }
    }
  });

  // 获取天气预报
  fastify.get<{
    Params: WeatherParams;
  }>('/weather/forecast/:city', {
    schema: {
      description: '获取指定城市的天气预报（未来4天）',
      tags: ['天气'],
      params: {
        type: 'object',
        properties: {
          city: { 
            type: 'string', 
            description: '城市名称或城市编码' 
          },
        },
        required: ['city'],
      },
      response: {
        200: {
          type: 'object',
          properties: {
            success: { type: 'boolean' },
            message: { type: 'string' },
            data: {
              type: 'object',
              properties: {
                type: { type: 'string' },
                weather: { type: 'object' },
                formatted: { type: 'object' }
              },
            },
          },
        },
      },
    },
    handler: async (request: FastifyRequest<{ Params: WeatherParams }>, reply: FastifyReply) => {
      try {
        const { city } = request.params;

        if (!weatherService.validateCity(city)) {
          return reply.status(400).send({
            success: false,
            message: '城市参数无效'
          });
        }

        const result = await weatherService.getForecastWeather(city);

        if (!result.success) {
          return reply.status(400).send(result);
        }

        const formatted = weatherService.formatWeatherData(result.data!.weather);

        return reply.send({
          success: result.success,
          message: result.message,
          data: {
            type: result.data!.type,
            weather: result.data!.weather,
            formatted
          }
        });

      } catch (error) {
        fastify.log.error(`天气预报查询失败: ${error instanceof Error ? error.message : String(error)}`);
        return reply.status(500).send({
          success: false,
          message: '服务器内部错误'
        });
      }
    }
  });
}